package com.itao.application;

import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.UrlFilenameViewController;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Component
public class AppSetting {
	private static TimeZone defaultTimeZone = TimeZone.getTimeZone("GMT+8:00");

	@Autowired(required = false)
	ServletContext servletContext;

	@Autowired(required = false)
	RequestMappingHandlerMapping requestMappingHandlerMapping;

	@Autowired(required = false)
	List<SimpleUrlHandlerMapping> simpleUrlHandlerMappings;

	@Autowired
	RequestMappingHandlerAdapter requestMappingHandlerAdapter;

	public static TimeZone getDefaultTimeZone() {
		return defaultTimeZone;
	}

	@PostConstruct
	public void initApp() {
		if (servletContext != null) {
			initWebApp();
		}
	}

	public void initWebApp() {
		String appVersion = servletContext.getInitParameter("appVersion");
		if (!StringUtils.hasText(appVersion)
				|| appVersion.equals("${appVersion}")) {
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd'T'HH:mm:ss");
			appVersion = format.format(new Date());
		}
		servletContext.setAttribute("appVersion", appVersion);

		// 10秒钟还连不上数据库的话就报错
		DriverManager.setLoginTimeout(10);

		/**
		 * 设置 url找不到mapping时的默认mapping
		 */
		if (requestMappingHandlerMapping != null) {
			requestMappingHandlerMapping.setDefaultHandler(defaultHandler());
		}

		/**
		 * 设置 AlwaysUseFullPath = true， 这样的mapping比较直观。
		 */
		if (simpleUrlHandlerMappings != null) {
			for (SimpleUrlHandlerMapping handlerMapping : simpleUrlHandlerMappings) {
				handlerMapping.setAlwaysUseFullPath(true);
			}
		}
	}

	@Bean
	public UrlFilenameViewController defaultHandler() {
		UrlFilenameViewController defaultHandler = new UrlFilenameViewController();
		return defaultHandler;
	}
}
